package org.orr.budgetpro.controller;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;

import org.orr.budgetpro.entities.Budget;
import org.orr.budgetpro.entities.User;
import org.orr.budgetpro.services.BudgetCalculator;
import org.orr.budgetpro.services.BudgetService;
import org.orr.budgetpro.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/explore")
public class ExploreController {
	@Autowired
	UserService userService;

	@Autowired
	BudgetService budgetService;

	@Autowired
	BudgetCalculator budgetCalculator;

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView getExplorePage(HttpServletRequest request,
			Principal principal) {
		ModelAndView modelView = new ModelAndView();

		User user = getCurrentUser(principal);
		Budget budget = budgetService.getBudgetByUserId(user.getUserId());

		modelView.addObject("expenseCategoryTotals",
				budgetCalculator.getExpenseCategoryTotals(budget));
		modelView.addObject("incomeSubtotal",
				budgetCalculator.getIncomeSubtotal(budget));
		modelView.addObject("expenseSubtotal",
				budgetCalculator.getExpenseSubtotal(budget));
		modelView.addObject("netBudgetTotal",
				budgetCalculator.getNetBudgetTotal(budget));

		return modelView;
	}

	protected User getCurrentUser(Principal principal) {
		User user = userService.getUser(principal.getName());

		if (user == null) {
			// If user isn't found, initialize a user and budget, and persist

			user = new User();
			user.setUserId(principal.getName());
			// In the future, this could be expanded to actually register the
			// user and get firstname, lastname, etc

			Budget budget = new Budget();
			budget.setUser(user);

			user.setBudget(budget);

			userService.saveUser(user);
			budgetService.saveBudget(budget);
		}

		return user;
	}
}
